<template>
  <div v-loading="loading">
    <div class="header-text">个人资料</div>
    <div class="main-content">
      <p style="margin-bottom: 22px">基本资料</p>
      <el-form
        ref="userInfoFormRef"
        :model="userInfoForm"
        status-icon
        :rules="rules"
        label-width="78px"
        size="large"
        style="width: 70%"
      >
        <el-form-item label="用户名" prop="account">
          <el-input
            v-model="userStore.userInfo.account"
            type="text"
            placeholder="请输入用户名"
            disabled
          />
        </el-form-item>
        <el-form-item label="头像" prop="avatar" required>
          <el-popover placement="right" :width="320" trigger="click">
            <template #reference>
              <el-avatar
                :size="80"
                :src="userInfoForm.avatar"
                style="cursor: pointer"
              />
            </template>
            <div style="display: flex">
              <div v-for="index in [1, 2, 3]">
                <el-avatar
                  :size="80"
                  :src="'male' + index + '.png'"
                  style="cursor: pointer"
                  @click="
                    () => {
                      userInfoForm.avatar = 'male' + index + '.png'
                    }
                  "
                />
                <el-avatar
                  :size="80"
                  :src="'female' + index + '.png'"
                  style="cursor: pointer"
                  @click="
                    () => {
                      userInfoForm.avatar = 'female' + index + '.png'
                    }
                  "
                />
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" required>
          <el-input
            v-model="userInfoForm.nickname"
            type="text"
            maxlength="20"
            placeholder="请输入昵称"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="个人介绍" prop="introduction">
          <el-input
            v-model="userInfoForm.introduction"
            type="textarea"
            maxlength="50"
            placeholder="请输入个人介绍"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(userInfoFormRef)">
            保存并修改
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reqChangeUserInfo, reqGetUserInfo } from '@/api/user'
import useUserStore from '@/store/modules/user'

onMounted(() => {
  getUserInfo()
})

const userStore = useUserStore()
const loading = ref(false)
const userInfoFormRef = ref<FormInstance>()
let userInfoForm = reactive({
  nickname: '',
  introduction: '',
  avatar: '',
})

const validateNickname = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入昵称'))
  } else {
    callback()
  }
}

const validateAvatar = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请选择头像'))
  } else if (value.includes('male')) {
    callback()
  } else {
    callback(new Error('请选择正确的头像'))
  }
}

const rules = reactive<FormRules<typeof userInfoForm>>({
  nickname: [{ validator: validateNickname, trigger: 'blur' }],
  avatar: [{ validator: validateAvatar, trigger: 'blur' }],
})

const getUserInfo = async () => {
  try {
    loading.value = true
    const { data } = await reqGetUserInfo()
    userInfoForm.nickname = data.nickname
    userInfoForm.avatar = data.avatar
    userInfoForm.introduction = data.introduction
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
      Promise.reject(new Error(error.message))
    }
  } finally {
    loading.value = false
  }
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        const { message } = await reqChangeUserInfo(userInfoForm)
        await userStore.getUserInfo()
        ElMessage.success(message)
      } catch (error) {
        if (error instanceof Error) {
          ElMessage.error(error.message)
          Promise.reject(new Error(error.message))
        }
      }
    } else {
      return false
    }
  })
}
</script>
<style scoped lang="scss">
.header-text {
  font-size: 18px;
  padding: 18px 22px;
  border-bottom: solid 1px var(--el-menu-border-color);
}

.main-content {
  padding: 18px 22px;
}
</style>
